package practise;

import org.junit.Test;

public class GetIntersectionNode {
    public static int listLen(ListNode head) {
        int ret = 0;
        ListNode cur = head;
        while(cur != null) {
            cur = cur.next;
            ret++;
        }
        return ret;
    }
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headB == null || headA == null) {
            return null;
        }

        ListNode curA = headA;
        ListNode curB = headB;
        int lenA = listLen(headA);
        int lenB = listLen(headB);

        int differ = lenA - lenB;
        if(differ > 0) {
            // A 比 B 长
            while((differ--) != 0) {
                curA = curA.next;
            }
        } else {
            differ = -differ;
            // B 比 A 长
            while((differ--) != 0) {
                curB = curB.next;
            }
        }

        while(curA != null && curB != null) {
            if(curA == curB) {
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }

    @Test
    public void test1() {

    }
}
